package com.cyzz.bookstore.modules.web;


import com.cyzz.bookstore.common.base.MyBaseController;
import com.cyzz.bookstore.common.json.BooksVO;
import com.cyzz.bookstore.common.json.StatisticVO;
import com.cyzz.bookstore.common.json.UserVO;
import com.cyzz.bookstore.common.myException.DBException;
import com.cyzz.bookstore.common.utils.DateUtils;
import com.cyzz.bookstore.modules.model.Book;
import com.cyzz.bookstore.modules.model.OrderForm;
import com.cyzz.bookstore.modules.model.User;
import com.cyzz.bookstore.modules.service.IBookService;
import com.cyzz.bookstore.modules.service.IOrderFormService;
import com.cyzz.bookstore.modules.service.IUserService;
import com.google.code.kaptcha.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author CBY
 * @since 2018-05-30
 */
@Controller
@RequestMapping("/user")
public class UserController extends MyBaseController {
	@Autowired
    private IUserService userService;
	@Autowired
    private IBookService bookService;
	@Autowired
    private IOrderFormService orderFormService;

    /**
     * 用户登录
     * @param form
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object getLoginUser1( @RequestBody UserVO.GetLoginForm form){
//        System.out.println(form.getUsername()+"      "+form.getPassword());
        User user = userService.selectUserByUsername(form.getUsername());
        String loginResult  = "";
        if(user.getStatus()==0){
            loginResult = "改账号已经被禁止使用！";
            return renderError(loginResult);
        }else if(!user.getPasswd().equals(form.getPassword())){
            loginResult = "用户名或密码错误！";
            return renderError(loginResult);
        }
        UserVO.CurrentUser u = UserVO.CurrentUser.getCurrentUser(user);
        return renderSuccess(u);
    }

    /**
     * 用户注册
     * @param form
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public Object register( @RequestBody UserVO.GetRegisterForm form){
//        System.out.println(form.getPassword()+" "+form.getRepassword());
        if(form.getPassword().equals(form.getRepassword())){
            User user = form.getUser();
            String message = "注册成功！";
            try {
                userService.insertUser(user);
            }catch (DBException ex){
                return renderError(ex.getMessage());
            }
            return renderSuccess(message);
        }else{
            String message = "两次密码不一致！";
            return renderError(message);
        }
    }

    /**
     * 管理员查看所有用户
     * @return
     */
    @RequestMapping(value = "/allUsers", method = RequestMethod.GET)
    @ResponseBody
    public Object getAllUsers(){
        List<UserVO.UserForAdimin> ulist = new ArrayList<>();
        try {
            List<User> list = userService.selectAllUser();
            for(User u:list){
                UserVO.UserForAdimin user = new UserVO.UserForAdimin();
                user.setStatus(u.getStatus());
                user.setType(u.getUserType());
                user.setUserid(u.getUserId());
                user.setUsername(u.getUserName());
                ulist.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderSuccess(e.getMessage());
        }
        return renderSuccess(ulist);
    }

    /**
     * 管理员修改顾客状态
     * @param id
     * @return
     */
    @RequestMapping(value = "/changeStatus", method = RequestMethod.GET)
    @ResponseBody
    public Object changeStatus( @RequestParam("userid") Long id){
        User user = userService.selectUserById(id);
        if(user.getStatus()==1){
            user.setStatus(0);
        }else{
            user.setStatus(1);
        }
        userService.updateUser(user);
        return renderSuccess();
    }

    /**
     * 用户修改信息
     * @param id
     * @param phone
     * @param address
     * @return
     */
    @RequestMapping(value = "/change", method = RequestMethod.GET)
    @ResponseBody
    public Object change( @RequestParam("userid") Long id,@RequestParam("phone") String phone,@RequestParam("address") String address){
        User user = userService.selectUserById(id);
        user.setTelephone(phone);
        user.setAddress(address);
        userService.updateUser(user);
        return renderSuccess();
    }

    /**
     * 顾客统计
     * @param id
     * @return
     */
    @RequestMapping(value = "/statisticForClient", method = RequestMethod.GET)
    @ResponseBody
    public Object statisticForClient( @RequestParam("userid") Long id){
        StatisticVO.Client client = new StatisticVO.Client();
        List<OrderForm> list  = orderFormService.selectOrderFormByClientId(id);
        List<BooksVO.getBookList> rlist = new ArrayList<>();
        int[] sums = new int[6];
        for(OrderForm of:list){
            Book b = null;
            b = bookService.selectBookById(of.getBookId());
            switch (b.getType()){
                case "经典名著":sums[0]+=of.getPurchaseCount();break;
                case "计算机与互联网":sums[1]+=of.getPurchaseCount();break;
                case "娱乐休闲":sums[2]+=of.getPurchaseCount();break;
                case "科普读物":sums[3]+=of.getPurchaseCount();break;
                case "生活图书":sums[4]+=of.getPurchaseCount();break;
                case "外语学习":sums[5]+=of.getPurchaseCount();break;
            }
        }
        client.setSums(sums);
        //推荐该顾客购买最多的分类的其他4本书
        String maxType = client.getMaxType(sums);
        List<Book> books = bookService.seleteBooksByType(maxType);
//        System.out.println("maxType:"+maxType+" "+books.size());
        int count=0;
        for(Book b:books){
            boolean flag = true;
            for(OrderForm o:list){
                if(o.getBookId()==b.getBookId()){
                    flag =false;
                    break;
                }
            }
            if(flag){
                count++;
                rlist.add(new BooksVO.getBookList(b));
                if (count==4){
                    break;
                }
            }
        }
        client.setBooks(rlist);
        return renderSuccess(client);
    }

    /**
     * 店铺统计
     * @param id
     * @return
     */
    @RequestMapping(value = "/statisticForShopkeeper", method = RequestMethod.GET)
    @ResponseBody
    public Object statisticForShopkeeper( @RequestParam("userid") Long id){
        StatisticVO.ShopKeeper shopKeeper = new StatisticVO.ShopKeeper();
        List<OrderForm> list = orderFormService.selectOrderFormByStoreId(id);
        Map<Long,Integer> bookMap = new HashMap<>();//统计销售量
        double[] seasonMoney = new double[4];
        for(OrderForm of:list){
//            System.out.println(of.getBookId()+" "+of.getPurchaseCount()+"k");
            shopKeeper.setTotalMoney(shopKeeper.getTotalMoney()+of.getPrice()*of.getPurchaseCount());
            if(bookMap.get(of.getBookId())!=null){
//                System.out.println(of.getBookId()+" "+of.getPurchaseCount()+"l");
                bookMap.put(of.getBookId(),of.getPurchaseCount()+bookMap.get(of.getBookId()));
            }else{
                bookMap.put(of.getBookId(),of.getPurchaseCount());
//                System.out.println(of.getBookId()+" "+of.getPurchaseCount()+"m");
            }
            switch (DateUtils.getSeason(of.getPurchaseDate())){
                case 1 : seasonMoney[0] += of.getPurchaseCount()*of.getPrice();break;
                case 2 : seasonMoney[1] += of.getPurchaseCount()*of.getPrice();break;
                case 3 : seasonMoney[2] += of.getPurchaseCount()*of.getPrice();break;
                case 4 : seasonMoney[3] += of.getPurchaseCount()*of.getPrice();break;
                default:
            }
        }
        System.out.println(bookMap.size());
        for(HashMap.Entry<Long,Integer> m:bookMap.entrySet()){
            BooksVO.BookMap bookM = new BooksVO.BookMap();
//            System.out.println(m.getKey()+" "+m.getValue());
            Book b = bookService.selectBookById(m.getKey());
            bookM.setTitle(b.getTitle());
            bookM.setNum(m.getValue());
            System.out.println(bookM.getTitle()+"    "+bookM.getNum());
            shopKeeper.addBook(bookM);
        }
        shopKeeper.sort();//排序
        shopKeeper.setSeasonMoney(seasonMoney);
        return renderSuccess(shopKeeper);
    }

    /**
     * 管理员统计
     * @return
     */
    @RequestMapping(value = "/statisticForManager", method = RequestMethod.GET)
    @ResponseBody
    public Object statisticForManager( /*@RequestParam("userid") Long id*/){
        StatisticVO.Manager manager = new StatisticVO.Manager();
        List<User> storeList = userService.selectUsersByUserType(1);
        for(User u:storeList){
            UserVO.UserMap userM = new UserVO.UserMap();
            userM.setUsername(u.getUserName());
            List<OrderForm> orderFormsList = orderFormService.selectOrderFormByStoreId(u.getUserId());
            for(OrderForm of:orderFormsList){
                userM.setMoney(userM.getMoney()+of.getPurchaseCount()*of.getPrice());
            }
            manager.addStore(userM);
        }
        List<OrderForm> allOrderForm = orderFormService.selectAllOrderForm();
        double[] seasonMoney = new double[4];
        for(OrderForm of:allOrderForm){
            switch (DateUtils.getSeason(of.getPurchaseDate())){
                case 1 : seasonMoney[0] += of.getPurchaseCount()*of.getPrice();break;
                case 2 : seasonMoney[1] += of.getPurchaseCount()*of.getPrice();break;
                case 3 : seasonMoney[2] += of.getPurchaseCount()*of.getPrice();break;
                case 4 : seasonMoney[3] += of.getPurchaseCount()*of.getPrice();break;
                default:
            }
        }
        manager.setSeasonMoney(seasonMoney);
        manager.sort();
        return renderSuccess(manager);
    }

}
